package team.epos.utils.util;

import org.apache.commons.dbcp.BasicDataSource;
import team.epos.utils.properties.DbProperties;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DbUtil {

    private static Properties conf = new Properties();
    private static BasicDataSource dataSource = new BasicDataSource();
    private static String url;
    private static String username;
    private static String password;
    private static String driver;


    public static void init(InputStream in) {
        try {
            conf.load(in);
            if (dataSource == null) {
                dataSource = new BasicDataSource();
            }
            DbProperties dbProperties = PropertiesBeanUtil.getBean(DbProperties.class, conf);
            url = dbProperties.getUrl();
            username = dbProperties.getUserName();
            password = dbProperties.getPassWord();
            driver = dbProperties.getDriverClass();
            int initSize = Integer.parseInt(dbProperties.getInitSize());
            int minIdle = Integer.parseInt(dbProperties.getMinIdle());
            int maxActive = Integer.parseInt(dbProperties.getMaxActive());
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            dataSource.setDriverClassName(driver);
            dataSource.setInitialSize(initSize);
            dataSource.setMinIdle(minIdle);
            dataSource.setMaxActive(maxActive);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Connection getConnection() {
        Connection con = null;
        try {
            con = dataSource.getConnection();
            return con;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
